Vue

Vue Router

Vue Router用法解析

Posted by Starrynight on 2024-06-13
Estimated Reading Time 5 Minutes
Words 1.2k In Total
Viewed Times

Vue Router 详细解析(基于 Vue 3)

Vue Router 是 Vue.js 官方的前端路由管理工具,适用于单页面应用(SPA)。在 Vue 3 中,Vue Router 进行了优化,使其更好地支持 Composition API


1. 安装 Vue Router

如果你的项目还没有 Vue Router,可以使用以下命令安装:

1
2
3
yarn add vue-router
# 或者
npm install vue-router

2. 创建 Vue Router 实例

在 Vue 3 中,我们需要 手动创建 router 实例并在 Vue 应用中使用它。

(1)新建 router/index.js(或 router/index.ts

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';

const routes = [
{ path: '/', component: Home }, // 首页
{ path: '/about', component: About } // 关于页面
];

const router = createRouter({
history: createWebHistory(), // HTML5 模式
routes
});

export default router;

(2)在 main.js(或 main.ts)中使用 router

1
2
3
4
5
6
7
import { createApp } from 'vue';
import App from './App.vue';
import router from './router'; // 导入 Vue Router

const app = createApp(App);
app.use(router); // 挂载路由
app.mount('#app');

3. 在 Vue 组件中使用路由

(1)基本的路由跳转

1
2
3
4
5
6
7
<template>
<nav>
<router-link to="/">首页</router-link>
<router-link to="/about">关于</router-link>
</nav>
<router-view />
</template>

📌 解释:

  • <router-link>:用于创建路由链接,类似 <a> 标签,但不会刷新页面。
  • <router-view>:用于显示匹配的组件。

(2)使用编程式导航

如果你想在 JavaScript 代码中 进行跳转,可以使用 router.push()

① 使用 router.push() 进行页面跳转

1
2
3
4
5
6
7
8
9
10
11
12
13
<script setup>
import { useRouter } from 'vue-router';

const router = useRouter();

const goToAbout = () => {
router.push('/about'); // 跳转到 /about
};
</script>

<template>
<button @click="goToAbout">跳转到关于页</button>
</template>

📌 router.push('/about') 会跳转到 /about,类似于 window.location.href,但不会刷新页面。

replace() 替换历史记录

1
router.replace('/about');
  • push() 会增加历史记录(可以返回上一个页面)。
  • replace() 不会增加历史记录(无法返回上一个页面)。

4. 动态路由

有时候,我们需要动态地根据 URL 传递参数,如:

1
2
/user/123
/user/456

可以使用动态路由匹配 :id

(1)在 router/index.js 中定义动态路由

1
2
3
const routes = [
{ path: '/user/:id', component: User }
];

(2)在 User.vue 组件中获取参数

1
2
3
4
5
6
7
8
9
10
<script setup>
import { useRoute } from 'vue-router';

const route = useRoute();
const userId = route.params.id;
</script>

<template>
<h2>用户 ID:{{ userId }}</h2>
</template>

📌 useRoute() 获取当前路由信息,其中 route.params.id 代表 :id 的值。


5. 路由守卫(导航守卫)

Vue Router 提供了 全局、路由独享、组件内部 3 种导航守卫,适用于权限控制、登录校验等场景。

(1)全局前置守卫(beforeEach

可以在进入路由之前 检查权限

1
2
3
4
5
6
7
8
router.beforeEach((to, from, next) => {
const isAuthenticated = localStorage.getItem('token'); // 是否已登录
if (to.path === '/admin' && !isAuthenticated) {
next('/login'); // 未登录,跳转到登录页面
} else {
next(); // 继续导航
}
});

(2)全局后置守卫(afterEach

用于 更改页面标题统计页面访问数据

1
2
3
router.afterEach((to) => {
document.title = to.meta.title || '默认标题';
});

(3)路由独享守卫

直接在 routes 配置里定义守卫。

1
2
3
4
5
6
7
8
9
10
11
12
13
const routes = [
{
path: '/dashboard',
component: Dashboard,
beforeEnter: (to, from, next) => {
if (!localStorage.getItem('token')) {
next('/login'); // 未登录跳转
} else {
next(); // 继续导航
}
}
}
];

6. 路由懒加载

在大型应用中,我们可以使用 Vue Router 的懒加载,只在需要时才加载组件,提高性能。

1
2
3
4
5
6
const routes = [
{
path: '/home',
component: () => import('../views/Home.vue') // 按需加载
}
];

7. 路由过渡动画

Vue Router 结合 Vue 的 transition 组件,可以为页面切换添加动画。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<template>
<router-link to="/">首页</router-link>
<router-link to="/about">关于</router-link>

<transition name="fade">
<router-view />
</transition>
</template>

<style>
.fade-enter-active, .fade-leave-active {
transition: opacity 0.5s;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
</style>

📌 解释:

  • fade-enter-from:进入动画开始时,透明度为 0
  • fade-enter-active:进入时应用 transition 过渡效果。
  • fade-leave-to:离开时透明度降为 0

总结

功能 代码示例
安装 Vue Router yarn add vue-router
创建路由实例 createRouter({ history: createWebHistory(), routes })
基本路由 <router-view> + <router-link to="/">
动态路由 { path: '/user/:id', component: User }
获取动态参数 const route = useRoute(); route.params.id
编程式导航 router.push('/about') / router.replace('/about')
路由守卫 router.beforeEach((to, from, next) => {})
懒加载 component: () => import('../views/Home.vue')
动画效果 transition 组件

Vue Router 在 Vue 3 中更加强大,与 Composition API 结合非常灵活。🚀


如果您喜欢此博客或发现它对您有用,则欢迎对此发表评论。 也欢迎您共享此博客,以便更多人可以参与。 如果博客中使用的图像侵犯了您的版权,请与作者联系以将其删除。 谢谢 !